package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo16Sort {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("join")

    val sc = new SparkContext(conf)

    //读取分数表
    val scoresRDD: RDD[String] = sc.textFile("data/score.txt")

    //取出学号和分数
    val idAndScoreRDD: RDD[(String, Int)] = scoresRDD.map(line => {
      val split: Array[String] = line.split(",")
      val id: String = split(0)
      val score: Int = split(2).toInt
      (id, score)
    })

    //计算学生的总分
    val sumScoreRDD: RDD[(String, Int)] = idAndScoreRDD.reduceByKey((x, y) => x + y)

    /**
     * sortBy ； 同一个列对数据进行排序，默认是升序
     * ascending = false：  降序
     *
     */

    val sortByRDD: RDD[(String, Int)] = sumScoreRDD.sortBy(kv => kv._2, ascending = false)

    //取前十，返回一个数组
    val top10: Array[(String, Int)] = sortByRDD.take(10)

    top10.foreach(println)
  }
}
